package com.example.springjdbc.hikaricp.demo.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@PropertySource(value = "classpath:/config/datasource.properties")
//@ConfigurationProperties(prefix = "datasource")
public class HiKaricpDataSourceFromConfigFileConfig {

    @Value(value = "${datasource.driverClass}")
    private String driverClass;
    @Value(value = "${datasource.url}")
    private String url;
    @Value(value = "${datasource.username}")
    private String username;
    @Value(value = "${datasource.password}")
    private String password;
    @Value(value = "${datasource.minimumIdle}")
    private int minimumIdle;
    @Value(value = "${datasource.maximumPoolSize}")
    private int maximumPoolSize;
    @Value(value = "${datasource.idleTimeout}")
    private long idleTimeout;
    @Value(value = "${datasource.connectionTimeout}")
    private long connectionTimeout;
    @Value(value = "${datasource.connectionTestQuery}")
    private String connectionTestQuery;
    @Value(value = "${datasource.validationTimeout}")
    private long validationTimeout;

    @Bean
    public DataSource dataSource() throws SQLException {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMinimumIdle(minimumIdle);
        dataSource.setMaximumPoolSize(maximumPoolSize);
        dataSource.setIdleTimeout(idleTimeout);
        dataSource.setConnectionTimeout(connectionTimeout);
        dataSource.setConnectionTestQuery(connectionTestQuery);
        dataSource.setValidationTimeout(validationTimeout);
        return dataSource;
    }
}
